package com.webdemo01.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdemo01.javabean.User;
import com.webdemo01.util.DBHandler;

public class QueryUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select id,name from servlet03_user";
		conn = DBHandler.newInstance().getConnection();
		int id = 0;
		String name = null;
		List<User> users = new ArrayList<User>();
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				id = rs.getInt("id");
				name = rs.getString("name");
				User user = new User();
				user.setId(id);
				user.setName(name);
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.setAttribute("users", users);
		request.getRequestDispatcher("/WEB-INF/jsp/show.jsp").forward(request,
				response);
	}

}
